package com.dongwu.config;

import java.io.File;
import java.util.Map;

import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.dongwu.common.constants.OSSClientConstants;
import com.dongwu.common.utils.Encodes;
import com.dongwu.common.utils.HttpClientUtils;
import com.gexin.fastjson.JSON;

/**
 * 阿里云VOD视频点播通过ossSDK上传
 * 
 * @author xyj
 *
 */
public class AliyunVodForOSS {
	/**
	 * 上传视频并返回视频详情
	 * 
	 * @param file
	 *            (文件)
	 * @param title
	 *            (视频标题)
	 * @return videoId (视频ID)
	 */
	public static String uploadVideo(File file, String title) {
		DefaultAcsClient aliyunClient;
		aliyunClient = new DefaultAcsClient(DefaultProfile.getProfile("cn-shanghai", OSSClientConstants.ACCESS_KEY_ID,
				OSSClientConstants.ACCESS_KEY_SECRET));

		CreateUploadVideoRequest request = new CreateUploadVideoRequest();
		CreateUploadVideoResponse response = null;
		try {
			/*
			 * 必选，视频源文件名称（必须带后缀, 支持 ".3gp", ".asf", ".avi", ".dat", ".dv",
			 * ".flv", ".f4v", ".gif", ".m2t", ".m3u8", ".m4v", ".mj2",
			 * ".mjpeg", ".mkv", ".mov", ".mp4", ".mpe", ".mpg", ".mpeg",
			 * ".mts", ".ogg", ".qt", ".rm", ".rmvb", ".swf", ".ts", ".vob",
			 * ".wmv", ".webm"".aac", ".ac3", ".acm", ".amr", ".ape", ".caf",
			 * ".flac", ".m4a", ".mp3", ".ra", ".wav", ".wma"）
			 */
			request.setFileName(file.getName());
			// 必选，视频标题
			request.setTitle(title);
			// // 可选，分类ID
			// request.setCateId(cateId);
			// // 可选，视频标签，多个用逗号分隔
			// request.setTags(tags);
			// // 可选，视频描述
			// request.setDescription(description);
			response = aliyunClient.getAcsResponse(request);
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		Map<String, Object> map = decodeBase64(response.getUploadAddress());
		Map<String, Object> mapauth = decodeBase64(response.getUploadAuth());

		// 初始化OSSClient
		OSSClient ossClient = AliyunOSSClientUtil.getOSSClient(map.get("Endpoint").toString(),
				mapauth.get("AccessKeyId").toString(), mapauth.get("AccessKeySecret").toString());
		// 通过OSS上传video到视频点播
		AliyunOSSClientUtil.uploadObject2OSS(ossClient, file, map.get("Bucket").toString(),
				map.get("FileName").toString(), mapauth.get("SecurityToken").toString());

		// Map<String,Object> videoUrl = getVideoUrl(response.getVideoId());
		return response.getVideoId();
	}

	/**
	 * 获取视频的播放地址
	 * 
	 * @param videoId
	 * @return
	 */
	public static Map<String, Object> getVideoUrl(String videoId) {
		Map<String, Object> videInfo = null;
		try {
			String Url = SignatureUtil.geturl(OSSClientConstants.ACCESS_KEY_ID, OSSClientConstants.ACCESS_KEY_SECRET,
					videoId, null, "GetPlayInfo");
			videInfo = HttpClientUtils.HttpGetResMap(Url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return videInfo;

	}

	/**
	 * base64解码并返回map<String,Object>
	 *
	 * @param code
	 * @return
	 */
	private static Map<String, Object> decodeBase64(String code) {
		byte[] getUploadAddress = Encodes.decodeBase64(code);
		Map<String, Object> map = JSON.parseObject(new String(getUploadAddress));
		return map;
	}
	// /**
	// * 阿里云公共参数
	// *
	// * @param code
	// * @return
	// */
	// private static String decodeBase64(String code) {
	// //获取当前日期作为version
	// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
	// String verison = df.format(new Date());
	// System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
	//
	//
	//// http://vod.cn-shanghai.aliyuncs.com/
	//// ?Format=json
	//// &Version=2017-03-21
	//// &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D
	//// &SignatureMethod=Hmac-SHA1
	//// &SignatureNonce=9166ab59-f445-4005-911d-664c1570df0f
	//// &SignatureVersion=1.0
	//// &Action=GetVideoPlayAuth
	//// &AccessKeyId=tkHh5O7431CgWayx
	//// &Timestamp=2017-03-29T09%3A22%3A32Z
	// StringBuffer sb=new StringBuffer();
	// sb.append("&Version=" + verison);
	// sb.append("&AccessKeyId=" + OSSClientConstants.ACCESS_KEY_ID);
	// sb.append("&SignatureMethod=Hmac-SHA1");
	// sb.append("&SignatureVersion=1.0");
	//
	// sb.append("&Signature=");
	// sb.append("&SignatureNonce="+generateRandom());
	// sb.append("&Timestamp="+generateTimestamp());
	//
	// return null;
	// }
	// /*生成当前UTC时间戳Time*/
	// private static String generateTimestamp() {
	// Date date = new Date(System.currentTimeMillis());
	// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
	// df.setTimeZone(new SimpleTimeZone(0, "GMT"));
	// return df.format(date);
	// }
	// public static String generateRandom() {
	// String signatureNonce = UUID.randomUUID().toString();
	// return signatureNonce;
	// }
}
